<!-- 应急演练详情 -->
<template>
  <div id="awdDetail" class="sceneDetail">
    <!-- <div style="color: rgb(27, 76, 184); margin-bottom: 15px">
          <div class="addressIcon"></div>
          <span>当前位置：</span>
          <span style="cursor: pointer" @click="returnPage">{{ title }}</span>
          <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
          <span style="color: #333">{{ drillDetail.name }}</span>
      </div> -->
    <div class="sceneStep">
      <!-- {{ processStatus }} -->
      <template>
        <div class="step-group">
          <Steps :current="currentIndex" direction="vertical" style="width: 100%">
            <Step
              title="演练前设置"
              @click.native="toPreCompeManage"
              content="提供演练前演练角色、成员、演练步骤的管理"
              :class="{ curStep: drillStatus == 1 }"
              :icon="drillStatus == 1 ? 'ios-refresh-circle' : ''"
            ></Step>
            <Step
              :title="'演练中管理' + (drillDetail.progress == 5 ? '(已暂停)' : '')"
              @click.native="toCompeingManage"
              content="提供演练过程中的控制,比如开启关闭演练、演练过程中步骤完成情况等"
              :class="{ curStep: drillStatus == 2 }"
              :icon="drillStatus == 2 ? 'ios-refresh-circle' : ''"
            ></Step>
            <Step
              title="演练后归档"
              @click.native="toCompeedManage"
              content="提供演练后报告等的管理和统计"
              :class="{ curStep: drillStatus == 3 }"
              :icon="drillStatus == 3 ? 'ios-refresh-circle' : ''"
            ></Step>
          </Steps>
          <p
            style="color: #f00"
            v-if="projectInfo.status == 3 && drillDetail.progress == 4 && endClearConfig"
          >
            【您的环境将于<Time
              :time="destoryTime"
              type="datetime"
            />时自动回收，若仍需保留，请在回收前重新开始配置演练】
          </p>
        </div>
      </template>
      <div class="countdown" v-if="drillDetail.progress != 4">
        <template v-if="drillDetail.progress != 5">
          <span v-if="drillStatus == 1">开始</span
          ><span v-if="drillStatus != 1">结束</span>倒计时：<b>
            <span>{{ time.h }}</span
            >:<span>{{ time.m }}</span
            >:<span>{{ time.s }}</span></b
          >
        </template>
        <strong v-else> 暂停中 </strong>
      </div>
      <div class="btn-group">
        <div class="flex">
          <Poptip
            confirm
            title="确定要释放本次比赛的资源吗？如果确定本次比赛的结果已经统计完毕,请继续."
            @on-ok="clearProject()"
            transfer
            word-wrap
            width="250"
          >
            <Button
              type="primary"
              :ghost="destoryProject() || disabledAllBtn()"
              :disabled="destoryProject() || disabledAllBtn()"
            >
              <img
                src="../../assets/scene/dis-not-deploy.png"
                alt=""
                v-if="destoryProject() || disabledAllBtn()"
              />
              <img src="../../assets/scene/not-deploy.png" alt="" v-else />
              <span v-if="projectInfo.status == 14 || projectInfo.status == 3">释放资源</span>
              <span v-else>{{ projectInfo.statusCHName }}</span>
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualization()"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../assets/scene/dis-screen.png" />可视化展示
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="确定要开始演练？"
            @on-ok="startOrStopDrill('2')"
            transfer
            v-if="drillDetail.progress != 4"
            word-wrap
          >
            <Button type="primary" :ghost="disabledStartCompete" :disabled="disabledStartCompete">
              <img
                src="../../assets/scene/dis-start-scene.png"
                alt=""
                v-if="disabledStartCompete"
              />
              <img src="../../assets/scene/start-scene.png" alt="" v-else />
              开始演练
            </Button>
          </Poptip>
          <!-- || this.processStatus !== 'stopped' -->
          <Button
            type="primary"
            @click="showModal()"
            v-if="drillDetail.progress == 4"
            :ghost="disabledAllBtn()"
            :disabled="disabledAllBtn()"
          >
            <img src="../../assets/scene/dis-start-scene.png" alt="" v-if="disabledAllBtn()" />
            <img src="../../assets/scene/start-scene.png" alt="" v-else />
            重新开始演练
          </Button>
          <Button
            type="primary"
            @click="showDelayModal()"
            v-if="drillStatus == 2"
            :ghost="disabledAllBtn()"
            :disabled="disabledAllBtn()"
          >
            <img src="../../assets/scene/dis-delay.png" alt="" v-if="disabledAllBtn()" />
            <img src="../../assets/scene/delay.png" alt="" v-else />
            延迟演练
          </Button>
          <!-- <Poptip
                      confirm
                      title="确定要重置环境？"
                      @on-ok="resetEnviron()"
                      transfer
                      v-if="drillDetail.progress == 4 && cloudType !== 'h3c'"
                      word-wrap>
                      <Button type="primary"  :ghost="disabledAllBtn() || resetStatus == 1" :disabled="disabledAllBtn() || resetStatus == 1">
                          <template v-if="resetStatus == 1">
                              <Progress :percent="resetProgress" :stroke-width="10" style="width:90px" v-if="resetStatus == 1 && drillDetail.progress == 4">
                                  <span>重置{{resetProgress}}%</span>
                              </Progress>
                          </template>
                          <template v-else>
                              <img src="../../assets/scene/dis-reset-network.png" alt="" height="16" v-if="disabledAllBtn()"/>
                              <img src="../../assets/scene/reset-network.png" alt="" height="16" v-else/>
                              重置环境
                          </template>
                          <Icon type="ios-information-circle-outline" :size="16" @click.stop="getResetDetail" v-if="resetFail" style="vertical-align:text-bottom;"/>
                      </Button>
                  </Poptip> -->
          <Poptip
            confirm
            title="确定要结束演练？"
            @on-ok="startOrStopDrill('4')"
            transfer
            word-wrap
          >
            <Button
              type="primary"
              :ghost="stopContestStatus || disabledAllBtn()"
              :disabled="stopContestStatus || disabledAllBtn()"
            >
              <img
                src="../../assets/scene/dis-stop-scene.png"
                alt=""
                v-if="stopContestStatus || disabledAllBtn()"
              />
              <img src="../../assets/scene/stop-scene.png" alt="" v-else />
              结束演练
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="确定要暂停演练？"
            @on-ok="startOrStopDrill(5)"
            transfer
            v-if="drillDetail.progress != 5"
            word-wrap
          >
            <Button
              type="primary"
              :ghost="drillDetail.progress != 2 || disabledAllBtn()"
              :disabled="drillDetail.progress != 2 || disabledAllBtn()"
            >
              <img
                src="../../assets/scene/dis-pause-scene.png"
                alt=""
                v-if="drillDetail.progress != 2 || disabledAllBtn()"
              />
              <img src="../../assets/scene/pause-scene.png" alt="" v-else />
              暂停演练
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="确定要恢复演练？"
            @on-ok="restoreCompetition"
            transfer
            v-if="drillDetail.progress == 5"
            word-wrap
          >
            <Button
              type="primary"
              :ghost="drillDetail.progress != 5 || disabledAllBtn()"
              :disabled="drillDetail.progress != 5 || disabledAllBtn()"
            >
              <img
                src="../../assets/scene/dis-recover-scene.png"
                alt=""
                v-if="drillDetail.progress != 5 || disabledAllBtn()"
              />
              <img src="../../assets/scene/recover-scene.png" alt="" v-else />
              恢复演练
            </Button>
          </Poptip>
          <Button type="primary" @click="boardModal = true"
            ><img src="../../assets/scene/dis-boardcast.png" alt="" />发送公告</Button
          >
          <!-- <Button type="primary" @click="gotoReportPage" v-if="drillDetail.progress == 4"><img src="../../assets/scene/btn-report.png">报告</Button> -->
          <Poptip
            confirm
            title="确定要清空场景公告及聊天消息？"
            @on-ok="clearSceneNoticeAndChat()"
            transfer
            word-wrap
          >
            <Button type="primary">清空场景公告及聊天信息</Button>
          </Poptip>
          <Button
            type="primary"
            @click="handleGoCircumstances"
            v-if="$store.state.common.sysConfig.modeConfig != '1'"
            >进入环境</Button
          >
        </div>
        <div style="margin-top: 5px">
          <span style="color: #ff9900; font-size: 14px">
            <Icon
              type="ios-information-circle-outline"
              :size="16"
            />开始演练前请先完成角色人员配置和演练步骤配置,如果已经完成配置,开始按钮不可点,请点击
          </span>
          <a @click="validateStart" :disabled="notOwn" style="font-size: 14px">校验</a>
        </div>
        <div style="margin-top: 5px" v-if="notOwn">
          <span style="color: #ff9900; font-size: 14px">
            <Icon type="ios-information-circle-outline" :size="16" />非本人创建的演练项目无法校验
          </span>
        </div>
        <!-- <div style="margin-top:5px;">
                  <span style="color:#ff9900;font-size:14px">
                      <Icon type="ios-information-circle-outline" :size="16"/>如果演练环境已经被改变，“重新开始演练”前请先“重置环境”
                  </span>
              </div> -->
        <!-- <div style="margin-top:5px;">
                  <span style="color:#ff9900;font-size:14px;">
                      <Icon type="ios-information-circle-outline" :size="16"/>演练最长时间间隔为一周,当前时间与演练结束时间间隔大于一周时不允许开始演练
                  </span>
              </div>	 -->
        <ChatRoom
          v-if="!notOwn"
          :drillId="drillid"
          :isDistributed="isDistributed"
          class="btn-chat"
          ref="chatRoom"
        ></ChatRoom>
      </div>
    </div>
    <div class="span-group">
      <span style="margin-right: 10px">
        演练结束后24小时是否自动销毁环境：<Tag color="blue">{{ endClearConfigShow }}</Tag>
        <Poptip
          confirm
          :title="changeEndClearConfigTip"
          :disabled="disChangeEndClearConfig"
          @on-ok="changEndClearConfig()"
        >
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            style="padding: 0"
            :disabled="disChangeEndClearConfig"
            size="small"
          ></Button>
        </Poptip>
      </span>
    </div>
    <!-- <TopologyShow v-if="preCompeManagePanelShow" step="pre"></TopologyShow> -->
    <Tabs class="demo-tabs-style2" v-if="preCompeManagePanelShow" v-model="preDefault">
      <TabPane label="演练步骤" name="step" :index="1">
        <TopologyShow ref="topologyShow" v-if="preDefault == 'step'" step="pre"></TopologyShow>
      </TabPane>
      <TabPane label="演练角色管理" name="accessGroup" :index="2">
        <AccessUserToGroup
          v-if="preDefault == 'accessGroup'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
          :hlConfig="hlConfig"
          :isDistributed="isDistributed"
          @setHasUser="setHasUser"
          step="pre"
        ></AccessUserToGroup>
      </TabPane>
      <TabPane label="接入机器分配" name="accessVm" :index="3">
        <AccessVmToUser
          v-if="preDefault == 'accessVm'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
          :hlConfig="hlConfig"
          :isDistributed="isDistributed"
        ></AccessVmToUser>
      </TabPane>
      <TabPane label="操作任务" name="task" :index="4">
        <Task v-if="preDefault == 'task'" :disabledAllBtn="disabledAllBtn()"></Task>
      </TabPane>
      <TabPane label="文件写入" name="qgawrite" :index="5">
        <qgawrite
          v-if="preDefault == 'qgawrite'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
        ></qgawrite>
      </TabPane>
      <TabPane label="执行命令" name="vmcmd" :index="6">
        <vmcmd
          v-if="preDefault == 'vmcmd'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
        ></vmcmd>
      </TabPane>
      <TabPane label="单次读取任务" name="onceReadFile" :index="7">
        <onceReadFile
          v-if="preDefault == 'onceReadFile'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
        ></onceReadFile>
      </TabPane>
      <!-- <TabPane label="循环读取任务" name="qgaloopread">
            <qgaloopread v-if="preDefault == 'qgaloopread'" :type="drillDetail.type" :disabledAllBtn ="disabledAllBtn()"></qgaloopread>
          </TabPane> -->
      <TabPane label="单次带外采集" name="oncecapture" :index="8">
        <oncecapture
          v-if="preDefault == 'oncecapture'"
          :type="drillDetail.type"
          :disabledAllBtn="disabledAllBtn()"
        ></oncecapture>
      </TabPane>
      <!-- <TabPane label="循环带外采集" name="loopcapture">
            <loopcapture v-if="preDefault == 'loopcapture'" :type="drillDetail.type" :disabledAllBtn ="disabledAllBtn()"></loopcapture>
          </TabPane> -->
      <TabPane label="Checker任务" name="checker" v-if="showYjChecker" :index="9">
        <Checker
          v-if="preDefault == 'checker'"
          :disabledAllBtn="disabledAllBtn()"
          :type="drillDetail.type"
        ></Checker>
      </TabPane>
      <TabPane
        v-if="emergencyConfig.collection"
        label="流量采集"
        name="trafficCollection"
        key="pre-trafficCollection"
        :index="10"
      >
        <trafficCollection
          :type="drillDetail.type"
          v-if="preDefault == 'trafficCollection'"
        ></trafficCollection>
      </TabPane>
      <TabPane v-if="emergencyConfig.flow" label="流量过滤" name="flow" key="pre-flow" :index="11">
        <Flow v-if="preDefault == 'flow'" :type="drillDetail.type"></Flow>
      </TabPane>
    </Tabs>
    <Tabs class="demo-tabs-style2" v-if="compeingManagePanelShow" v-model="midDefault">
      <!-- <TabPane label="演练题目统计" name="targetTeamMid">
            <TargetTeamMid v-if="midDefault == 'targetTeamMid'" :type="0" :poll="true" :drillDetail="drillDetail" :hlConfig="hlConfig"></TargetTeamMid>
        </TabPane> -->
      <TabPane label="演练步骤" name="step" :index="1">
        <TopologyShow ref="topologyShow" v-if="midDefault == 'step'" step="mid"></TopologyShow>
      </TabPane>
      <TabPane label="选手接入机器录屏" name="tab6" :index="2">
        <screenController v-if="midDefault == 'tab6'"></screenController>
      </TabPane>
      <TabPane label="网络行为" name="networkBehavior" :index="3" v-if="showYjFlow">
        <networkBehavior
          v-if="midDefault == 'networkBehavior'"
          :showMonitoring="showMonitoring"
          @toTrafficRetrieval="toTrafficRetrieval"
        />
      </TabPane>
      <!-- 暂时不需要威胁事件 -->
      <TabPane label="威胁事件" name="threatEvent" :index="4" v-if="showYjFlow">
        <threatEvent v-if="midDefault == 'threatEvent'" />
      </TabPane>
      <TabPane label="流量检索" name="trafficRetrieval" :index="5" v-if="showYjFlow">
        <trafficRetrieval
          v-if="midDefault == 'trafficRetrieval'"
          :trafficRetrievalParams="trafficRetrievalParams"
        />
      </TabPane>
      <!-- <TabPane label="违规行为" name="violations" :index="6">
              <violations v-if="midDefault == 'violations'" />
          </TabPane> -->
      <!-- <TabPane label="势力方排行统计" name="adwRankingStatic" v-if="![2, 1].includes(hlConfig)">
          <adwRankingStatic v-if ="midDefault == 'adwRankingStatic'" :poll="true" :hlConfig="hlConfig"></adwRankingStatic>
          </TabPane>
          <TabPane label="团队排行统计" name="teamRankStatic">
          <teamRankStatic v-if ="midDefault == 'teamRankStatic'" :poll="true" :hlConfig="hlConfig" :disabledAllBtn="disabledAllBtn()"></teamRankStatic>
          </TabPane>
          <TabPane label="攻击得分统计" name="attackSuccess">
          <scoreRecordStatic v-if ="midDefault == 'attackSuccess'" :type="1"  :sceneType ="0" :poll="true" :hlConfig="hlConfig"></scoreRecordStatic>
          </TabPane>
          <TabPane label="提交统计" name="submitRecord" key="end-submit-record" v-if="hlConfig==1">
      <submitRecord :isBasicScore="false" v-if ="midDefault == 'submitRecord'" :type="0"  :showStatus="true"></submitRecord>
    </TabPane>
          <TabPane label="防守失分统计" name="defenceSuccess" v-if="[2, 1].includes(hlConfig)"> 
              <scoreRecordStatic v-if ="midDefault == 'defenceSuccess'" :type="2" :sceneType ="0" :poll="true" :hlConfig="hlConfig"></scoreRecordStatic>
          </TabPane>
          <TabPane label="异常失分统计" name="unabnormalScore" v-if="[2, 1].includes(hlConfig)">
          <scoreRecordStatic v-if ="midDefault == 'unabnormalScore'" :type="3" :sceneType ="0" :poll="true" :hlConfig="hlConfig"></scoreRecordStatic>
          </TabPane>
          <TabPane label="防守得分统计" name="defenceSuccess" v-if="![2, 1].includes(hlConfig)">
              <scoreRecordStatic v-if ="midDefault == 'defenceSuccess'" :type="5" :sceneType ="0" :poll="true" :hlConfig="hlConfig"></scoreRecordStatic>
           </TabPane>
           <TabPane label="异常得分统计" name="abnormalScore" v-if="![2, 1].includes(hlConfig)">
          <scoreRecordStatic v-if ="midDefault == 'abnormalScore'" :type="4" :sceneType ="0" :poll="true" :hlConfig="hlConfig"></scoreRecordStatic>
          </TabPane>
          <TabPane label="题目异常日志" name="targetExceptionLog">
              <TargetExceptionLog v-if ="midDefault == 'targetExceptionLog'" :type="0"></TargetExceptionLog>
          </TabPane>
          <TabPane label="环境管理" name="environManage">
              <EnvironManage v-if ="midDefault == 'environManage'"></EnvironManage>
          </TabPane> -->
    </Tabs>
    <Tabs class="demo-tabs-style2" v-if="compeedManagePanelShow" v-model="endDefault">
      <TabPane label="演练记录" name="drillRecord" :index="1">
        <SummaryReport
          type="record"
          v-if="endDefault == 'drillRecord'"
          :disabledAllBtn="disabledAllBtn()"
        ></SummaryReport>
        <!-- <DrillRecord v-if ="endDefault == 'drillRecord'" :disabledAllBtn="disabledAllBtn()"></DrillRecord> -->
      </TabPane>
      <TabPane label="备注描述" name="remarks" :index="2">
        <SummaryReport
          type="remarks"
          v-if="endDefault == 'remarks'"
          :disabledAllBtn="disabledAllBtn()"
        ></SummaryReport>
        <!-- <DrillRecord v-if ="endDefault == 'drillRecord'" :disabledAllBtn="disabledAllBtn()"></DrillRecord> -->
      </TabPane>
      <TabPane label="演练总结" name="summaryReport" :index="3">
        <SummaryReport
          type="report"
          v-if="endDefault == 'summaryReport'"
          :disabledAllBtn="disabledAllBtn()"
        ></SummaryReport>
      </TabPane>
      <TabPane label="演练归档" name="attachment" :index="4">
        <SummaryReport
          type="file"
          v-if="endDefault == 'attachment'"
          :disabledAllBtn="disabledAllBtn()"
        ></SummaryReport>
      </TabPane>
      <TabPane
        label="流量归档"
        name="trafficArchiving"
        key="end-trafficArchiving"
        :index="5"
        v-if="showYjFlow"
      >
        <trafficArchiving v-if="endDefault == 'trafficArchiving'" />
      </TabPane>
      <TabPane label="录屏回放" name="tab6-end" :index="6">
        <screenController v-if="endDefault == 'tab6-end'" :poll="false"></screenController>
      </TabPane>
    </Tabs>
    <Modal v-model="boardModal" title="发送公告" :width="650" footer-hide>
      <board
        v-if="boardModal"
        @hideModal="hideModal"
        :isDistributed="isDistributed"
        :isMainRange="isMainRange"
      ></board>
    </Modal>
    <Modal
      v-model="sceneModal.show"
      :title="sceneModal.title"
      :loading="sceneModal.loading"
      :mask-closable="false"
      @on-visible-change="visibleChange"
      @on-ok="saveScene('formValidate')"
      @on-cancel="handleReset('formValidate')"
      :width="600"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="时间" prop="Dates">
          <DatePicker
            :editable="false"
            type="datetimerange"
            :value="formValidate.Dates"
            format="yyyy-MM-dd HH:mm"
            placement="bottom-start"
            confirm
            ref="datePicker"
            placeholder="选择日期"
            style="width: 280px"
            transfer
            @on-ok="clickOkBtn"
            @on-clear="clickClearBtn"
            @on-open-change="switchOpenChange"
            @on-change="changeDates"
          ></DatePicker>
          <p style="color: #ff9900; font-size: 10px">
            选择同一天的时间段，请双击要选择的日期
          </p>
          <!-- ，最长时间间隔为一周 -->
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="sceneDelayModal.show"
      :title="sceneDelayModal.title"
      :loading="sceneDelayModal.loading"
      :mask-closable="false"
      @on-ok="saveSceneDelayTime('formValidate1')"
      @on-cancel="handleReset('formValidate1')"
      :width="600"
    >
      <Form ref="formValidate1" :model="formValidate" :rules="delayRuleValidate" :label-width="80">
        <FormItem label="结束时间" prop="endDate">
          <DatePicker
            :editable="false"
            type="datetime"
            :value="formValidate.endDate"
            format="yyyy-MM-dd HH:mm"
            placement="bottom-start"
            placeholder="选择日期"
            style="width: 280px"
            transfer
            @on-open-change="endDateOpenChange"
            @on-change="changeEndDate"
            @on-ok="clickOkBtn"
          ></DatePicker>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="tipModal.show" :title="tipModal.title" width="300" footer-hide>
      <h4>
        <Icon
          type="ios-loading"
          size="24"
          class="demo-spin-icon-load"
          style="margin-right: 24px"
        ></Icon
        >{{ tipModal.content }}
      </h4>
    </Modal>
    <Modal v-model="resetDetailModal.show" :title="resetDetailModal.title" width="800" footer-hide>
      <Button type="primary" ghost size="small" @click="rebuildAllFailVm" v-if="resetFail">
        <img
          src="../../assets/scene/dis-reset-network.png"
          alt=""
          style="vertical-align: middle"
        />重置所有重置失败节点
      </Button>
      <Table :columns="resetCol" :data="resetInfo.msgs" style="margin-top: 10px"></Table>
    </Modal>
  </div>
</template>

<script>
import SummaryReport from '@/view/drill_compete/page/yj/summaryReport'
import DrillRecord from '@/view/drill_compete/page/yj/drillRecord'
import Task from '@/view/drill_compete/page/yj/task'
import qgawrite from '@/view/drill_compete/page/yj/task/qgawrite.vue'
import onceReadFile from '@/view/drill_compete/page/yj/task/onceReadFile.vue'
import qgaloopread from '@/view/drill_compete/page/yj/task/qgaloopread.vue'
import oncecapture from '@/view/drill_compete/page/yj/task/oncecapture.vue'
import loopcapture from '@/view/drill_compete/page/yj/task/outband.vue'
import vmcmd from '@/view/drill_compete/page/yj/task/vmcmd.vue'
// import TopologyShow from '@/view/drill_compete/page/yj/topologyShow'
import TopologyShow from '@/view/drill_compete/page/yj/process'
// import RangeInformation from '@/view/drill_compete/page/rangeInformation'
// import submitRecord from '@/view/drill_compete/page/statistics/submitRecord.vue'
// import ReportList from '@/view/drill_compete/page/report-list'
// import BasicScoreConfig from '@/view/drill_compete/page/basicScoreConfig'
// import TargetTeam from '@/view/drill_compete/page/targetTeam' //靶机
import AccessVmToUser from '@/view/drill_compete/page/accessVmToUser'
// import Flow from '@/view/drill_compete/page/flow'
import Flow from '@/view/drill_compete/page/flow-new'
// import TargetTeamMid from '@/view/drill_compete/page/targetTeam-mid'
import screenController from '@/view/drill_compete/page/screenController'
// import FlagCommitLoop from '@/view/drill_compete/page/flagCommitLoop'
import Checker from '@/view/drill_compete/page/checker'
// import FlagOutLoop from '@/view/drill_compete/page/task_new/flagOutLoop.vue'
// import FlagVmOnce from '@/view/drill_compete/page/flagVmOnce'
import AccessUserToGroup from '@/view/drill_compete/page/accessUserToGroup'
// import TargetExceptionLog from '@/view/drill_compete/page/awdTargetExceptionLog'
// import adwRankingStatic from '@/view/drill_compete/page/statistics/partyRankStatic.vue'
// import scoreRecordStatic from '@/view/drill_compete/page/statistics/scoreRecordStatic.vue'
// import adwDrillIntegral from '@/view/drill_compete/page/statistics/awdDrillIntegral.vue'
// import teamRankStatic from '@/view/drill_compete/page/statistics/teamRankStatic.vue'
import board from '@/components/board-cast/drillBoardcast.vue'
// import EnvironManage from '@/view/drill_compete/page/environManage.vue'
import ChatRoom from '@/components/chatRoom/chatRoom'
import trafficCollection from '@/view/drill_compete/page/componentHW/trafficCollection'
import encryption from '@/libs/encryption.js'
import {
  getSceneInfo,
  updateSceneProgress,
  setSceneCycle,
  modifyScene,
  batchOpVm,
  batchOpVmLog,
  batchOpVmLogOnce,
  rebuildVm,
  addSceneCycle
} from '@/api/drill_compete'
import { clearProject } from '@/api/competition'
import { getstatusbyprjid, getCompeteSummarize } from '@/api/drill'
import { getDictInfoByName } from '@/api/dict.js'
import { clearSceneNoticeAndChat } from '@/api/boardcast_new.js'
import { operateTest, getTestStatus } from '@/api/process/task.js'
import timer from '@/mixin/timer'
import commonFun from './mixin.js'
import recoverTime from '@/mixin/recoverTime'
import destroyEnv from '@/mixin/destroyEnvironmentMixin'
// import resetSceneMixin from '@/mixin/resetSceneMixin'; //重置按钮注释，就注释
import ReconnectingWebSocket from 'reconnecting-websocket'
import networkBehavior from '@/view/drill_compete/page/componentHW/networkBehavior'
import threatEvent from '@/view/drill_compete/page/componentHW/threatEvent'
import trafficRetrieval from '@/view/drill_compete/page/componentHW/trafficRetrieval'
import violations from '@/view/drill_compete/page/componentHW/violations'
import trafficArchiving from '@/view/drill_compete/page/componentHW/trafficArchiving'
export default {
  name: 'scenes',
  components: {
    // TargetTeam, //靶机--演练前后
    // adwRankingStatic, //势力方排名统计
    // scoreRecordStatic,
    // adwDrillIntegral, //积分
    // Flow, //流量过滤
    Flow, //流量过滤
    // TargetTeamMid, //靶机--演练中（type="mid"）会轮询，需传show,
    // FlagCommitLoop, //flag持续提交
    Checker, //check任务
    // FlagOutLoop, //
    // FlagVmOnce, //Flag服务器配置 //emergencyConfig
    qgawrite,
    onceReadFile,
    oncecapture,
    qgaloopread,
    loopcapture,
    vmcmd,
    AccessVmToUser, //（环境）接入机器
    AccessUserToGroup, //（演练用户管理）分配用户
    // TargetExceptionLog,//靶标异常日志
    // teamRankStatic, //团队得分排名
    board,
    screenController,
    // EnvironManage,
    ChatRoom,
    // ReportList,
    // submitRecord,
    // BasicScoreConfig,
    // RangeInformation,
    SummaryReport,
    DrillRecord,
    Task,
    TopologyShow,
    trafficCollection, // 流量采集
    networkBehavior, // 网络行为
    threatEvent, // 威胁事件
    trafficRetrieval, // 流量检索
    violations, // 违规行为
    trafficArchiving // 流量归档
  },
  mixins: [timer, commonFun, recoverTime, destroyEnv], //resetSceneMixin
  data() {
    let September = sessionStorage.getItem('November')
    September = JSON.parse(encryption.SelfUseDecrypt(September))
    const validateDate = (rule, value, callback) => {
      //验证只能填入数字
      //验证警戒值
      if (value) {
        if (!this.formValidate.startTime || !this.formValidate.endTime) {
          callback(new Error('请选择时间'))
        } else if (
          new Date(this.formValidate.endTime).getTime() -
            new Date(this.formValidate.startTime).getTime() <
          60 * 60 * 1000
        ) {
          callback(new Error('起止时间最小间隔一个小时'))
        } else {
          callback()
        }
        // else if (new Date(value[1]).getTime() - new Date(value[0]).getTime() > 7*24*60*60*1000) {
        //     callback(new Error('最长时间间隔为一周'));
        // }
      } else {
        callback()
      }
    }
    const validateDelayDate = (rule, value, callback) => {
      //验证只能填入数字
      //验证警戒值
      if (value) {
        if (new Date(value).getTime() - new Date(this.drillDetail.endTime).getTime() <= 0) {
          callback(new Error('选择的时间必须大于当前结束时间'))
        } else {
          callback()
        }
        // else if (new Date(value).getTime() - new Date(this.drillDetail.startTime).getTime() > 7*24*60*60*1000) {
        //   callback(new Error('最长时间间隔为一周'));
        // }
      } else {
        callback(new Error('请选择时间'))
      }
    }
    return {
      isDistributed: 0,
      isMainRange: 0,
      hlConfig: 2,
      showHLVisBtn: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      projectId: this.$route.query.prjid,
      drillid: this.$route.query.id,
      drillName: this.$route.query.name,
      drillDetail: {},
      testid: this.$route.query.id,
      currentIndex: 0,
      preCompeManagePanelShow: true,
      compeingManagePanelShow: false,
      compeedManagePanelShow: false,
      startContestStatus: false, // 是否开始过，除赛前均为true
      stopContestStatus: false, // 是否已停止，除赛中均为true
      preDefault: '',
      midDefault: '',
      endDefault: '',
      drillStatus: '', // 比赛状态 1赛前 2赛中 3赛后
      backObj: {
        path: '/emergencyDefenseDrill',
        name: 'emergencyDefenseDrill',
        query: {
          page: this.$route.query.page
        },
        meta: {
          requireAuth: true
        }
      },
      project: {
        drillitemname: this.$route.query.name,
        projectid: this.$route.query.prjid,
        drillitemid: this.$route.query.id,
        testId: this.$route.query.id
      },
      testid: this.$route.query.id, //工程场景id
      projectInfo: {},
      timeoutP: {},
      timeout: {},
      boardModal: false,
      compReportModal: false,
      sceneModal: {
        show: false,
        title: '修改时间',
        loading: true,
        type: 1,
        width: 550
      },
      sceneDelayModal: {
        show: false,
        title: '延迟比赛时间',
        loading: true,
        type: 1,
        width: 550
      },
      formValidate: {
        cycleTime: 1,
        description: '',
        endTime: '',
        extension: '',
        iconPath: '',
        id: '',
        name: '',
        progress: 0, // 0.准备中、1.准备完毕、2.开始中、3.裁判评判阶段、4.结束
        projectId: '',
        projectName: '',
        startTime: '',
        status: 1, //0 ：不启用 1：启用
        type: 0, //0.对抗演练、1.攻防赛、2夺旗赛、3知识赛、4渗透演练
        Dates: [],
        stMode: 0,
        endDate: ''
      },
      ruleValidate: {
        Dates: [
          { required: true, type: 'array', message: '不能为空', trigger: 'change' },
          { validator: validateDate, trigger: 'change' }
        ]
      },
      delayRuleValidate: {
        endDate: [{ validator: validateDelayDate, trigger: 'change' }]
      },
      disabledDestroy: false, // 是否禁止销毁，默认为false
      destoryTime: '',
      tipModal: {
        title: '提示',
        show: false,
        content: ''
      },
      resetProgress: 0,
      resetInfo: {},
      resetStatus: 0,
      resetFail: false,
      resetDetailModal: {
        title: '重置详情',
        show: false
      },
      resetCol: [
        {
          title: '虚拟机名称',
          key: 'name'
        },
        {
          title: '实例名称',
          key: 'instanceName'
        },
        {
          title: '系统类型',
          key: 'sysType'
        },
        {
          title: '子网络名称',
          key: 'networkName'
        },
        {
          title: '镜像名称',
          key: 'imageName'
        },
        {
          title: '状态',
          key: 'errMsg',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.errMsg ? 'red' : 'green'
                }
              },
              params.row.errMsg ? '重置失败' : '重置成功'
            )
          }
        },
        {
          title: '错误信息',
          key: 'errMsg',
          render: (h, params) => {
            return h('span', params.row.errMsg || '无')
          }
        }
      ],
      ws: '',
      processStatus: '',
      // 控制显示隐藏流量采集、流量过滤（定制）
      emergencyConfig: {
        flow: false,
        collection: false
      },
      showYjChecker: false,
      showYjFlow: false, //应急演练 演练中显示网络行为、威胁事件、流量检索tab，演练后显示流量归档功能
      showMonitoring: true, // 显示监控行为,
      trafficRetrievalParams: {
        //  网络行为切换到流量检索参数
        showFlag: false
      }
    }
  },
  filters: {},
  provide() {
    return {
      parent: this,
      detailParent: this
    }
  },
  beforeDestroy() {
    clearTimeout(this.timeout)
    clearInterval(this.timeoutP)
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/awdDrill') {
      next()
    } else {
      //跳转至非红蓝对抗页面，清空存储的查询条件
      sessionStorage.removeItem('queryObj')
      next()
    }
  },
  computed: {
    disabledStartCompete() {
      return this.startContestStatus || this.disabledAllBtn() || this.disStartCompete
      // || new Date(this.drillDetail.endTime).getTime() - this.serveTime > 7*24*60*60*1000
      // || this.processStatus !== 'initialized'
    },
    notOwn() {
      return this.drillDetail.creator !== this.USER_ID
    },
    extension() {
      return (this.drillDetail.extension && JSON.parse(this.drillDetail.extension)) || {}
    },
    title() {
      //当前菜单显示名
      return this.$store.getters.pageTitle
    }
  },
  watch: {
    // processStatus(val){
    //     if(val === 'stopped' && this.drillStatus === 2){
    //         this.startOrStopDrill('4')
    //     }
    // }
  },
  mounted() {
    this.getDrillDetail(true, true).then((data) => {
      this.$store.commit('addBreadItem', { name: this.drillDetail.name })
      //判断是否可以开始比赛
      this.canStartCompete(this.drillDetail.type)
    })
    this.$store.dispatch('common/getSysConfigShow', 'showYjChecker').then((data) => {
      this.showYjChecker = data
    })
    this.$store.dispatch('common/getSysConfigShow', 'showYjFlow').then((data) => {
      this.showYjFlow = data
    })
    this.getProjectInfo()
    sessionStorage.removeItem('vmCurrentPage')
    this.getDictInfoByName('emergencyConfig') // 流量过滤、采集
    this.getDictInfoByName('isShowHLVisBtn')
  },
  methods: {
    // 网络行为切换到流量检索
    toTrafficRetrieval(row) {
      console.log('121212', row)
      this.trafficRetrievalParams = row
      this.changeMidTab('trafficRetrieval')
    },
    changeMidTab(name) {
      if (name !== 'trafficRetrieval') {
        this.trafficRetrievalParams = {
          //  网络行为切换到流量检索参数
          showFlag: false
        }
      }
      this.midDefault = name
      if (name == 'accessUser') {
      }
    },
    //进入环境
    handleGoCircumstances() {
      if (this.$store.state.common.sysConfig.modeConfig == '2') {
        this.$Message.info('未授权功能，请联系管理员')
      } else if (this.$store.state.common.sysConfig.modeConfig == 'jizhi2024') {
        window.open(
          `/14-topologyProject/index.html#/topologyDisplay/topologys?projectId=${this.$route.query.prjid}`
        )
      }
    },
    // 查询是否需要展示额外定制的可视化
    getDictInfoByName(name) {
      getDictInfoByName({ name }).then(({ code, attribute, message }) => {
        if (code == 1) {
          if (name == 'isShowHLVisBtn') {
            this.showHLVisBtn = attribute.data.value === '1'
          }
          if (name == 'emergencyConfig') {
            let { flow = 0, collection = 0 } = JSON.parse(attribute.data.value)
            this.emergencyConfig = {
              flow: flow === 1,
              collection: collection === 1
            }
          }
        } else {
          if (name == 'isShowHLVisBtn') {
            this.showHLVisBtn = false
          }
          if (name == 'emergencyConfig') {
            this.emergencyConfig = {
              flow: false,
              collection: false
            }
          }
          if (message === '没查询到数据') {
            // 该数据没有查询到时，并不需要提示错误信息，默认不展示额外的可视化跳转连接
            return
          }
          this.$Message.error(message)
        }
      })
    },
    // 查询工程信息，主要用于获取状态，判断需要展示的内容
    getProjectInfo() {
      if (!this.$route.query.prjid) {
        return
      }
      this.disabledDestroy = false
      getstatusbyprjid(this.$route.query.prjid).then((data) => {
        if (data.code == 1) {
          this.projectInfo = data.attribute.project
          this.webSocketStatus()
          // 这个判断条件应该是有误的，后续可能是需要改正的，处于这些状态不再更新工程信息
          if ([0, 10, 14].includes(this.projectInfo.status)) {
            // 0:未部署；10:os待修改；14:清空部署失败
            clearInterval(this.timeoutP)
          }
        } else if (data.code == -2) {
          this.projectInfo.statusCHName = '工程不存在'
          this.disabledDestroy = true
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    
    // 查询对抗演练详情，同时确定是否需要进入对应阶段，是否需要展示倒计时
    async getDrillDetail(needChangeStep, needServiceTime) {
      await Promise.all([this.getTestStatus(), getSceneInfo(this.drillid)]).then(
        ([status, data]) => {
          // 获取场景详情
          let startTimeChange = data.data.startTime != this.drillDetail.startTime // 开始时间是否已修改
          let endTimeChange = data.data.endTime != this.drillDetail.endTime // 结束时间是否已修改
          this.drillDetail = data.data
          if (JSON.parse(this.drillDetail.extension).isDistributed) {
            this.isDistributed = JSON.parse(this.drillDetail.extension).isDistributed
          }
          if (JSON.parse(this.drillDetail.extension).isMainRange) {
            this.isMainRange = JSON.parse(this.drillDetail.extension).isMainRange
          }
          this.hlConfig = JSON.parse(this.drillDetail.extension).hlConfig
          this.destoryTime = new Date(this.drillDetail.endTime).getTime() + 24 * 60 * 60 * 1000 // 结束后24小时自动销毁，计算销毁时间
          this.formValidate = Object.assign(this.formValidate, data.data)
          this.formValidate.Dates = [this.formValidate.startTime, this.formValidate.endTime]
          if (this.drillDetail.progress == 0 || this.drillDetail.progress == 1) {
            // 赛前
            if (needChangeStep) {
              this.toPreCompeManage()
            }
            if (needServiceTime || startTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              // mixin中的方法，转入时间大于服务器时间时，每隔30秒更新一次服务器时间，同时计算倒计时时间
              this.getServeTime(new Date(this.drillDetail.startTime).getTime())
            }
            this.drillStatus = 1 // 比赛状态 1赛前
            this.startContestStatus = false // 赛前允许开始比赛，后续逻辑都做了取反，所以需要设置为false
            this.stopContestStatus = true
            // 初始化试验
            if (this.processStatus === 'stopped' && !this.isOperateTest) {
              this.operateTest('init')
            }
          } else if (
            this.drillDetail.progress == 2 ||
            this.drillDetail.progress == 3 ||
            this.drillDetail.progress == 5
          ) {
            // 赛中
            if (needChangeStep) {
              this.toCompeingManage()
            }
            if (needServiceTime || endTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              this.getServeTime(new Date(this.drillDetail.endTime).getTime())
            }
            this.drillStatus = 2 // 比赛状态 2赛中
            this.startContestStatus = true
            this.stopContestStatus = false // 赛中允许停止比赛，后续逻辑都做了取反，所以需要设置为false
            // 开始试验
            if (this.processStatus === 'initialized' && !this.isOperateTest) {
              this.operateTest('start')
            }
            if (this.processStatus === 'stopped') {
              this.opTaskListNew(4)
            }
            if (this.processStatus === 'paused' && this.drillDetail.progress !== 5) {
              this.opTaskListNew(5)
            }
            if (this.processStatus === 'running' && this.drillDetail.progress === 5) {
              this.restoreCompetition()
            }
          } else if (this.drillDetail.progress == 4) {
            // 赛后
            if (needChangeStep) {
              this.toCompeedManage()
            }
            if (needServiceTime || endTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              this.getServeTime(new Date(this.drillDetail.endTime).getTime())
            }
            this.drillStatus = 3 // 比赛状态 3赛后
            this.startContestStatus = true
            this.stopContestStatus = true
            // 结束试验
            if (['running', 'stopping'].includes(this.processStatus) && !this.isOperateTest) {
              this.operateTest('stop')
            }
          }
        }
      )
      return this.drillDetail
    },
    // 关闭模态框时，清空对应模态框的数据，重置校验
    handleReset(name) {
      this.$refs[name].resetFields()
      this.iconSrc = ''
      this.formValidate.iconPath = ''
    },
    // 取消时，设置模态框按钮的等待状态
    cancelLoading(modal) {
      modal.loading = false
      setTimeout(() => {
        modal.loading = true
      })
    },
    // 重新开始比赛，打开设置起止时间的模态框
    showModal() {
      this.sceneModal.show = true
      this.sceneModal.type = '2'
    },
    // 重新开始的演练时间设置完成后的保存操作
    saveScene(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.formValidate))
          if (new Date(data.startTime).getTime() > new Date(data.endTime).getTime()) {
            this.$Message.error('表单输入有误，开始时间不能大于结束时间!')
            this.cancelLoading(this.sceneModal)
            return
          }
          delete data.Dates
          this.modifyScene(data.id, data, 'restart')
        } else {
          this.$Message.error('表单输入有误，请查看页面信息后重新输入!')
          this.cancelLoading(this.sceneModal)
        }
      })
    },
    // 延迟演练的时间设置完成后的保存操作
    saveSceneDelayTime(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.formValidate))
          delete data.Dates
          data.endTime = data.endDate
          delete data.endDate
          this.modifyScene(data.id, data, 'delay')
        } else {
          this.$Message.error('表单输入有误，请查看页面信息后重新输入!')
          this.cancelLoading(this.sceneDelayModal)
        }
      })
    },
    changEndClearConfig() {
      let data = { endClearConfig: this.endClearConfig ? 0 : 1 }
      this.modifyExtension(data, 'changeEndClearConfig')
    },
    modifyExtension(data, type) {
      let extension = { ...this.extension }
      for (let key in data) {
        extension[key] = data[key]
      }
      let formValidate = { extension: JSON.stringify(extension) }
      this.modifyScene(this.formValidate.id, formValidate, type).then(() => {
        this.drillDetail.extension = JSON.stringify(extension)
      })
    },
    // 修改比赛，延迟或重新开始攻防演练，修改后重新获取竞赛信息
    async modifyScene(id, data, type) {
      if (type === 'restart' && this.processStatus === 'stopped') {
        await this.operateTest('init')
      }
      modifyScene(id, data, type)
        .then((data) => {
          if (data.code == 1) {
            this.sceneModal.show = false
            this.sceneDelayModal.show = false
            if (type == 'delay') {
              // this.addSceneCycle();
              this.$Message.info('延迟成功')
              setTimeout(() => {
                this.getDrillDetail(false, true)
              }, 2000)
            } else if (type === 'changeEndClearConfig') {
              this.$Message.info('切换结束后是否销毁环境成功')
              setTimeout(() => {
                this.getDrillDetail(true, true)
              }, 2000)
            } else {
              setTimeout(() => {
                this.getDrillDetail(true, true)
              }, 2000)
              if (type == 'restart') {
                this.$Message.info('重新开始演练成功')
              }
            }
          } else {
            this.cancelLoading(this.sceneModal)
            this.cancelLoading(this.sceneDelayModal)
            this.$Message.warning(data.message)
          }
        })
        .catch((error) => {
          this.cancelLoading(this.sceneModal)
          this.cancelLoading(this.sceneDelayModal)
          this.$Message.error(error)
        })
    },
    // 可视化页面跳转
    showVisualization() {
      let oToken = localStorage.getItem('token')
      window.open(
        `${window.location.origin}/YingJi/index.html?id=${this.$route.query.id}&token=${oToken}&projectId=${this.$route.query.prjid}&creator=${this.USER_ID}`,
        '_black'
      )
    },
    // 额外可视化页面跳转
    showChoosableVisualization(type) {
      let oToken = localStorage.getItem('token')
      let contestId = this.$route.query.id
      let projectId = this.$route.query.prjid
      switch (type) {
        case 1: // 定制可视化
          //window.open(`http://localhost:8080/msgData12.html?contestId=${contestId}&token=${oToken}&projectId=${projectId}&taskName=${this.drillDetail.name}`, '_black');
          window.open(
            `${window.location.origin}/three.test12/msgData12.html?contestId=${contestId}&token=${oToken}&projectId=${projectId}&taskName=${this.drillDetail.name}`,
            '_black'
          )
          break
        case 2: // 天蝎可视化
          window.open(
            `${window.location.origin}/three.test12/toolData12.html?contestId=${contestId}&token=${oToken}&projectId=${projectId}`,
            '_black'
          )
          break
        case 3: // 大屏可视化
          window.open(
            `${window.location.origin}/ScreenCityVisual/#/viewPage?projectId=${projectId}&token=${oToken}&networkId=`,
            '_black'
          )
          break
      }
    },
    // 展示演练前设置页面
    toPreCompeManage() {
      this.preDefault = 'step'
      this.midDefault = ''
      this.endDefault = ''
      this.currentIndex = 0
      setTimeout(() => {
        this.preCompeManagePanelShow = true
        this.compeingManagePanelShow = false
        this.compeedManagePanelShow = false
      })
    },
    // 展示演练中设置页面
    toCompeingManage() {
      if (this.drillDetail.progress == 0 || this.drillDetail.progress == 1) {
        return
      }
      this.preDefault = ''
      this.midDefault = 'step'
      this.endDefault = ''
      this.currentIndex = 1
      setTimeout(() => {
        this.preCompeManagePanelShow = false
        this.compeingManagePanelShow = true
        this.compeedManagePanelShow = false
      })
    },
    // 展示演练后设置页面
    toCompeedManage() {
      if (this.drillDetail.progress != 4) {
        return
      }
      this.preDefault = ''
      this.midDefault = ''
      this.endDefault = 'drillRecord'
      this.currentIndex = 2
      setTimeout(() => {
        this.preCompeManagePanelShow = false
        this.compeingManagePanelShow = false
        this.compeedManagePanelShow = true
      })
    },
    // 恢复暂停的演练
    async restoreCompetition() {
      await this.startOrStopDrill('recover', '恢复')
      await this.restoreCompetition_minixs(this.drillid)
      this.tipModal.show = false
    },
    // 修改演练进度状态，并重新获取详情，开始操作还要额外设置周期信息
    async changeCompetitionStatus(status, op) {
      let result = 'notReq'
      if (status == 2 && this.processStatus === 'initialized') {
        result = await this.operateTest('start', false).catch((error) => {
          this.$Message.error(`${op}失败`)
        })
      } else if (
        status == 4 &&
        (this.processStatus === 'running' || this.processStatus === 'stopping')
      ) {
        result = await this.operateTest('stop', false).catch((error) => {
          this.$Message.error(`${op}失败`)
        })
      } else if (status == 5 && this.processStatus === 'running') {
        result = await this.operateTest('pause', false).catch((error) => {
          this.$Message.error(`${op}失败`)
        })
      } else if (status == 'recover' && this.processStatus === 'paused') {
        result = await this.operateTest('recover', false).catch((error) => {
          this.$Message.error(`${op}失败`)
        })
        this.tipModal.show = false
      }
      if (!result) {
        this.tipModal.show = false
        return
      }
      if (status !== 'recover') {
        result &&
          updateSceneProgress(this.drillid, status)
            .then((data) => {
              if (data.code == 1) {
                console.log('调用改变状态', op)
                this.$Message.info(`${op}成功`)
                this.tipModal.show = false
                this.getDrillDetail(true, true)
              }
            })
            .catch((error) => {
              this.$Message.error(error.message)
              this.tipModal.show = false
            })
      }
    },
    // 手动校验是否可以开始演练
    validateStart() {
      this.canStartCompete(this.drillDetail.type).then((data) => {
        this.$Message.info('校验完成')
      })
    },
    // 操作试验
    operateTest(op, showMessage = true) {
      this.isOperateTest = true
      return new Promise((resolve, reject) => {
        operateTest(this.testid, op)
          .then((data) => {
            if (data.code === 1) {
              this.processStatus = data.data.status
              if (this.processStatus === 'stopping') {
                this.operateTest('stop', false)
              }
              // if(this.processStatus === 'paused'){
              //     this.operateTest('pause', false);
              // }
              // if(this.processStatus === 'stopped' && this.drillStatus === 2){
              //     this.startOrStopDrill('4')
              // }
              resolve(data.data.status)
            } else {
              let msg = data.message + ''
              if (this.processStatus === 'stopping' && msg.includes('才可以停止')) {
                // 23058
                // console.log('stop 后状态为stoping,再次调用小概率会报'实验在运行中才可以停止')
                this.processStatus = 'stopped'
              } else {
                this.$Message.error(data.message)
              }

              resolve()
            }
          })
          .catch((error) => {
            reject()
          })
          .finally(() => {
            this.isOperateTest = false
          })
      })
    },
    // 获取试验状态
    getTestStatus() {
      return new Promise((resolve, reject) => {
        getTestStatus(this.testid)
          .then((data) => {
            if (data.code == 1) {
              this.processStatus = data.data.status
              resolve(this.processStatus)
            } else {
              this.$Message.error(data.message)
              reject()
            }
          })
          .catch((error) => {
            reject()
          })
      })
    },
    // 启动或停止演练，操作成功后需要一键操作配置的任务
    startOrStopDrill(status) {
      if (status == 2) {
        // 启动，需要校验是否可以启动，时间设置是否合理
        this.canStartCompete(this.drillDetail.type).then((data) => {
          if (!data) {
            this.$Message.warning('请检查角色成员及演练步骤是否配置完成')
            return
          } else {
            // if(new Date(this.drillDetail.endTime) - new Date().getTime() > 7*24*60*60*1000){
            //     this.$Message.warning('无法开始演练，演练最长时间间隔为一周');
            //     return;
            // }
            this.opTaskListNew(status)
          }
        })
        this.tipModal.content = '正在开始演练...请稍后!!'
      } else if (status == 5) {
        this.tipModal.content = '正在暂停演练...请稍后!!'
        this.opTaskListNew(status)
      } else if (status == 'recover') {
        this.tipModal.content = '正在恢复比赛...请稍后!!'
        this.opTaskListNew(status)
      } else {
        // 停止
        this.tipModal.content = '正在停止演练...请稍后!!'
        this.opTaskListNew(status)
      }
    },
    // 一键操作，启动或者停止演练配置好的任务，
    async opTaskListNew(status) {
      this.tipModal.show = true
      let str
      let statusName = '结束'
      if (status == 2) {
        // 开始
        str = 'start'
        statusName = '开始'
      } else if (status == 5) {
        str = 'pause'
        statusName = '暂停'
      } else if (status == 'recover') {
        str = 'recover'
        statusName = '恢复'
      } else {
        str = 'stop'
        statusName = '结束'
        if (this.drillDetail.progress == 5) {
          await this.startOrStopDrill('recover', '恢复')
        }
      }
      this.changeCompetitionStatus(status, statusName)
    },
    // 配置场景周期
    setSceneCycle() {
      setSceneCycle(this.drillid).then((data) => {
        if (data.code == 1) {
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    // 释放资源
    clearProject() {
      this.disabledDestroy = true
      clearProject(this.$route.query.prjid)
        .then((data) => {
          if (data.code == 1 || data.code == 3) {
            this.$Message.info('环境清空中...')
            clearInterval(this.timeoutP)
            this.timeoutP = setInterval((data) => {
              this.getProjectInfo()
            }, 3000)
          } else {
            this.$Message.warning(data.message)
          }
          this.disabledDestroy = false
        })
        .catch((error) => {
          this.disabledDestroy = false
        })
    },
    // 隐藏发送公告的模态框
    hideModal() {
      this.boardModal = false
    },
    // 是否允许销毁工程，false才允许销毁
    destoryProject() {
      return (
        this.disabledDestroy ||
        !this.startContestStatus ||
        !this.stopContestStatus ||
        !(this.projectInfo.status == 3 || this.projectInfo.status == 14)
      )
    },
    // 回到列表页
    returnPage() {
      this.$router.push(this.backObj)
    },
    // 跳转至报告页
    gotoReportPage() {
      const { href } = this.$router.resolve({
        name: 'rbdReport',
        query: {
          id: this.$route.query.id,
          hlConfig: this.hlConfig
        }
      })
      window.open(href, '_blank')
    },
    // 部署不成功或者创建者不是自己的数据结果为真，控制本组件和子组件部分按钮是否可点
    disabledAllBtn() {
      if (this.projectInfo.status != 3 || this.notOwn) {
        return true
      }
      if (JSON.parse(this.drillDetail.extension).isDistributed) {
        if (JSON.parse(this.drillDetail.extension).isMainRange != 1) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
      // return this.projectInfo.status != 3 || this.notOwn;
    },
    // 重置环境
    resetEnviron() {
      this.tipModal.show = true
      this.tipModal.content = '正在重置环境...请稍后!!'
      batchOpVm(this.projectId, 'rebuild')
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('操作成功')
            this.batchOpVmLog()
          } else {
            this.$Message.error(data.message)
          }
          this.tipModal.show = false
        })
        .catch((error) => {
          this.$Message.error('环境重置失败')
          this.tipModal.show = false
        })
    },
    // 查询环境重置记录
    batchOpVmLog(isFirst) {
      debugger
      batchOpVmLog({
        pageIndex: 1,
        pageSize: 10,
        projectId: this.$route.query.prjid,
        action: 'rebuild'
      })
        .then((data) => {
          if (data.code == 1) {
            if (data.data.items.length > 0) {
              //重置过
              let id = data.data.items[0].id
              this.batchOpVmLogDetail(id, isFirst)
            } else {
              //未重置
              this.resetStatus = 0
            }
          } else {
            this.$Message.error(data.messsage)
          }
        })
        .catch((error) => {
          this.$Message.error('查询重置详情失败')
        })
    },
    // 查询最近一条重置记录的详情，并计算进度，重置未完成则每两秒重新获取并计算一次
    batchOpVmLogDetail(id, isFirst) {
      batchOpVmLogOnce(id)
        .then((data) => {
          if (data.code == 1) {
            this.resetInfo = data.data
            this.resetInfo.finished = this.resetInfo.finished || 0
            this.resetProgress = parseInt((this.resetInfo.finished / this.resetInfo.total) * 100)
            if (this.resetInfo.finished == this.resetInfo.total) {
              this.resetStatus = 2 // 重置完成
              if (this.resetInfo.msgs.filter((item) => item.errMsg).length > 0) {
                this.resetFail = true
                if (!isFirst) {
                  this.$Message.error('重置失败')
                }
              } else {
                this.resetFail = false
                if (!isFirst) {
                  this.$Message.info('重置成功')
                }
              }
            } else if (this.resetInfo.finished < this.resetInfo.total) {
              this.resetStatus = 1 //重置中
            }
            if (this.resetStatus != 2) {
              setTimeout(() => {
                this.batchOpVmLogDetail(id)
              }, 2000)
            }
          } else {
            this.$Message.error(data.messsage)
          }
        })
        .catch((error) => {
          this.$Message.error('查询重置详情失败')
        })
    },
    // 重置存在失败节点时，打开失败节点重置模态框
    getResetDetail() {
      this.resetDetailModal.show = true
    },
    // 批量操作重置失败的节点
    rebuildAllFailVm() {
      this.tipModal.show = true
      this.tipModal.content = '正在重置环境...请稍后!!'
      let proArr = this.resetInfo.msgs
        .filter((item) => item.errMsg)
        .map(async (vm) => {
          await this.rebuildVm(vm.id)
        })
      Promise.all(proArr)
        .then((data) => {
          this.tipModal.show = false
          this.$Message.info('重置完成')
        })
        .catch((error) => {
          this.$Message.info('重置失败')
        })
    },
    // 重置指定的节点，轮训调用实现批量操作
    rebuildVm(id) {
      return new Promise((resolve, reject) => {
        rebuildVm(id)
          .then((data) => {
            if (data.code == 1) {
              resolve(data)
            } else {
              reject()
            }
          })
          .catch((error) => {
            reject()
          })
      })
    },
    // 打开设置延迟演练的模态框
    showDelayModal() {
      this.sceneDelayModal.show = true
      this.$set(this.formValidate, 'endDate', this.drillDetail.endTime)
    },
    // 延长比赛时用于添加比赛周期
    addSceneCycle() {
      let sceneId = this.$route.query.id
      addSceneCycle(sceneId)
        .then((data) => {
          if (data.code == 1) {
          } else {
            this.$Message.error(data.message)
          }
        })
        .catch((error) => {
          this.$Message.error('创建场景周期失败!')
        })
    },
    // 清空场景公告及聊天消息
    clearSceneNoticeAndChat() {
      const msg = this.$Message.loading({
        content: '正在清空...',
        duration: 0,
        closable: true
      })
      let sceneId = this.$route.query.id
      clearSceneNoticeAndChat(sceneId)
        .then((data) => {
          setTimeout(msg, 1000)
          setTimeout(() => {
            if (data.code == 1) {
              this.$Message.info('清空成功')
              this.$refs['chatRoom'].clearChatMsg()
            } else {
              this.$Message.info('清空失败')
            }
          }, 1100)
        })
        .catch((error) => {
          setTimeout(msg, 1000)
          setTimeout(() => {
            this.$Message.info('清空失败')
          }, 1100)
        })
    },
    // 试验状态
    setProcessStatus(val) {
      this.processStatus = val
    },
    // 获取卡夫卡工程告警消息
    webSocketStatus() {
      let url = location.hostname
      // this.ws = new ReconnectingWebSocket(`ws://172.172.100.1:9001/ws`);
      //    this.ws = new ReconnectingWebSocket(`ws://${url}:9001/ws`);
      this.ws = new ReconnectingWebSocket(`ws://${url}/wss/ws`)
      this.ws.addEventListener('open', () => {
        this.ws.send(JSON.stringify({ type: 'NETTING', projectId: `${this.projectId}` }))
      })
      this.ws.addEventListener('message', (evt) => {
        let received_msg
        try {
          received_msg = JSON.parse(evt.data)
          let msg = JSON.parse(received_msg.policy)
          msg.length > 0 && this.$refs['topologyShow'].showNotice(msg[0])
          // msg.length > 0 && this.$Notice.success({
          //     title: msg[0].action,
          //     desc: `攻击类型：【${msg[0].name}】 危险等级：】${msg[0].threat}】`,
          //     duration: 30
          // });
        } catch (error) {}
      })
      this.ws.addEventListener('close', () => {
        console.log('close')
      })
      this.ws.addEventListener('error', () => {
        console.log('error')
      })
    }
  }
}
</script>
<style scoped src="./detail.css"></style>
